home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4039 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: simple code, argc, argv, strcmp()
  5. Date: Thu, 1 Feb 1996 12:51:04 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9602011151.AA04526@dxmint.cern.ch>
  8. References: <11f7cc$17261a.3b3@daprez>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. otisg@panther.middlebury.edu (Otis Gospodnetic) writes:
  14.  
  15. >usage: <program> -e [SourceFile] RemoteFile
  16. >        or
  17. >       <program> -d [InFile]
  18. >
  19. >if the person doesn't use this right the program is supposed to call Usage()
  20. >which is not here, but it's in my code, and if the person calls the program
  21. >the correct way one of the two actions should be taken (encode or decode).
  22. >
  23. >Problem - I am doing something wrong and I almost always end up calling
  24. >Usage() even if I use the program correctly.
  25. >
  26. >int main (int argc, char **argv) {
  27. >
  28. >  if (!strcmp(argv[1],"-d") || !strcmp(argv[1],"-e")) {
  29. >    Usage();
  30. >  }
  31. ...
  32. >
  33. >Can someone see what's wrong with this ?
  34. >am I not using strcmp() right ?
  35.  
  36. Right :-)
  37.  
  38. Your code is equivalent to:
  39.  
  40.     if (strcmp(argv[1],"-d") == 0 || strcmp(argv[1],"-e") == 0) Usage();
  41.  
  42. Which means that any time the program is correctly invoked, it will call
  43. Usage!
  44.  
  45. So:
  46.  
  47. 1. Never use ! with strcmp.  It's a good way to shoot yourself in the foot.
  48.  
  49. 2. Always check what a function is supposed to return before using it.
  50.    strcmp returns 0 when the strings are equal.
  51.  
  52. 3. Are you sure you didn't mean && when you wrote ||?  Even if !strcmp()
  53.    would have worked as you thought it did, the || operator would have
  54.    caused the expression inside the if statement to _always_ evaluate to 1.
  55.  
  56. Dan
  57. -- 
  58. Dan Pop
  59. CERN, CN Division
  60. Email: danpop@mail.cern.ch 
  61. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  62.